﻿import store from './store.js';

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "D+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "H+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/([y|Y]+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

function parseDate(dt) {
    if (!dt) return null;
    if (dt instanceof Date) {
        return dt;
    }
    try{
        var dt1 = new Date(dt);
        if (dt1 instanceof Date && !isNaN(dt1)) {
            return dt1;
        }
    }catch(e){}

    dt = String(dt);
    dt = dt.replace(/\-/g, '/').replace(/年|月/g, '/').replace("日", "");
    if (dt.length == 16) {
        //有时候服务器返回的时间中没有包含秒   yyyy-MM-dd HH:mm, 这样的格式 ios转化以后就变成 null了
        dt = dt + ":00";
    }
    dt = new Date(dt);
    return dt;
}


//格式化日期
function formatDate(e, t) {
    if (!e) return "";
    e = parseDate(e);
    t = t || "yyyy-MM-dd";
    function r(e, t) {
        for (var r = 0, n = t - (e + "").length; r < n; r++)
            e = "0" + e;
        return e + ""
    }
    if (typeof (e) == "string") {
        var m = e.match(/\/Date\((\d+)\)\//);
        if (m) {
            e = new Date(parseInt(m[1]))
        } else {
            if (e.length <= 8 && e.indexOf(":") != -1) {
                e = "1970-01-01 " + e;
            }
            e = parseDate(e);
        }
    }
    return t.replace(/yyyy|YYYY/, e.getFullYear()).replace(/yy|YY/, r(e.getFullYear() % 100, 2))
        .replace(/M{2}/, r(e.getMonth() + 1, 2))
        .replace(/M{1}/, r(e.getMonth() + 1, 1))
        .replace(/D{2}|d{2}/, r(e.getDate(), 2)).replace(/d|D/g, e.getDate())
        .replace(/D{1}|d{1}/, r(e.getDate(), 1))
        .replace(/h+|H+/, r(e.getHours(), 2)).replace(/h|H/g, e.getHours())
        .replace(/i+|I+|m+/, r(e.getMinutes(), 2)).replace(/i|I|m/g, e.getMinutes())
        .replace(/s+|S+/, r(e.getSeconds(), 2)).replace(/s|S/g, e.getSeconds())
        .replace(/w/g, e.getDay()).replace(/W/g, ["日", "一", "二", "三", "四", "五", "六"][e.getDay()])
}

//加上x天，x周，x月，x年
function addDate(dt, day, tp) {
    if (typeof (dt) == "string") {
        dt = parseDate(dt);
    }
    //tp day, week, month, year
    tp = !tp ? "day" : tp.toLowerCase()
    switch (tp) {
        case "day":
            return new Date(dt.getTime() + (day * 24 * 60 * 60 * 1000))
        case "week":
            return new Date(dt.getTime() + (day * 7 * 24 * 60 * 60 * 1000))
        case "month":
            return new Date(dt.getFullYear(), dt.getMonth() + day, dt.getDate())
        case "year":
            return new Date(dt.getFullYear() + day, dt.getMonth(), dt.getDate())
    }
    return dt
}

//取每周/月/年 最后一天
function lastDate(dt, tp) {
    //tp Mmonth, Week, Year
    dt = parseDate(dt);
    tp = tp.toLowerCase()
    var newDt = dt
    switch (tp) {
        case "year":
            newDt = new Date(dt.getFullYear() + 1, 0, 0)
            break

        case "month":
            newDt = new Date(dt.getFullYear(), dt.getMonth() + 1, 0)
            break;
        case "week":
            var day = dt.getDay()
            newDt = addDate(dt, 7 - day)
            break;
    }
    return newDt
}

//取每周/月/年 第一天
function firstDate(dt, tp) {
    //tp Mmonth, Week, Year
    dt = parseDate(dt);
    tp = tp.toLowerCase()
    var newDt = dt
    switch (tp) {
        case "year":
            newDt = new Date(dt.getFullYear(), 0, 1)
            break

        case "month":
            newDt = new Date(dt.getFullYear(), dt.getMonth(), 1)
            break;
        case "week":
            var day = dt.getDay()
            if (day == 0) {
                day = 7;
            }
            newDt = addDate(dt, 1 - day)
            break;
    }
    return newDt
}

//两个日期间差几天
function betweenDay(dt1, dt2) {
    dt1 = parseDate(dt1);
    dt2 = parseDate(dt2);
    dt1 = new Date(dt1.getFullYear(), dt1.getMonth(), dt1.getDate())
    dt2 = new Date(dt2.getFullYear(), dt2.getMonth(), dt2.getDate())
    return (dt1.getTime() - dt2.getTime()) / (24 * 60 * 60 * 1000)
}

function getDefaultValue(value, psearch) {

    if (value == "[]") {
        return [];
    }
    if (value == "{}") {
        return {};
    }
    let user = store.user;
    let f3var = user?.f3var || {
        StudentCount: 0,
        StudentCallCount: 0,
        StudentLeavCount: 0,
        StudentSickCount: 0,
        StudentCallBL: ""
    };

    //{{学校名称}};{{当前用户ID}};{{当前用户}};{{当前日期}};{{在册学生数}};{{出勤学生数}};{{事假学生数}};{{病假学生数}};{{学生出勤率}}
    if (typeof (value) == "string" && value.startsWith("{")) {
        let today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        today.setMilliseconds(0);
        switch (value) {
            case "{{学校名称}}":
                return user ? user.SchollName : "";
            case "{{在册学生数}}":
                return f3var.StudentCount;
            case "{{出勤学生数}}":
                return f3var.StudentCallCount;
            case "{{事假学生数}}":
                return f3var.StudentLeavCount;
            case "{{病假学生数}}":
                return f3var.StudentSickCount;
            case "{{学生出勤率}}":
                return f3var.StudentCallBL;
            case "{{当日食谱}}":
                return f3var.CookBookStr;
            case "{{当日早餐}}":
                return f3var.CookBook?.ZaoCan;
            case "{{当日早点}}":
                return f3var.CookBook?.ZaoDian;
            case "{{当日午餐}}":
                return f3var.CookBook?.WuCan;
            case "{{当日下午点}}":
                return f3var.CookBook?.XiaWuDian;
            case "{{当日晚餐}}":
                return f3var.CookBook?.WanCan;
            case "{UserID}":
            case "{{当前用户ID}}":
                return user ? user.UserID : 0;
            case "{UserName}":
            case "{{当前用户}}":
                return user ? user.Name : "";

            case "{Now}":
            case "{{当前时间}}":
                return new Date();
            case "{NowS}":
                return (new Date()).format("yyyy-MM-dd HH:mm:ss");

            case "{Today}":
            case "{{当前日期}}":
                return today;
            case "{TodayS}":
                return formatDate(today, "YYYY-MM-DD");

            case "{Yestday}":
                return addDate(today, -1, 'day');
            case "{YestdayS}":
                return formatDate(addDate(today, -1, 'day'), "YYYY-MM-DD");

            case "{NextDay}":
                return addDate(today, 1, 'day');
            case "{NextDayS}":
                return formatDate(addDate(today, 1, 'day'), "YYYY-MM-DD");

            case "{WeekF}":
                return firstDate(today, 'week');
            case "{WeekFS}":
                return formatDate(firstDate(today, 'week'), "YYYY-MM-DD");
            case "{WeekL}":
                return lastDate(today, 'week');
            case "{WeekLS}":
                return formatDate(lastDate(today, 'week'), "YYYY-MM-DD");

            case "{MonthF}":
                return firstDate(today, 'month');
            case "{MonthFS}":
                return formatDate(firstDate(today, 'month'), "YYYY-MM-DD");
            case "{MonthL}":
                return lastDate(today, 'month');
            case "{MonthLS}":
                return formatDate(lastDate(today, 'month'), "YYYY-MM-DD");


            case "{YearF}":
                return firstDate(today, 'year');
            case "{YearFS}":
                return formatDate(firstDate(today, 'year'), "YYYY-MM-DD");
            case "{YearL}":
                return lastDate(today, 'year');
            case "{YearLS}":
                return formatDate(lastDate(today, 'year'), "YYYY-MM-DD");
        }
        let key = value.substr(1, value.length - 2);
        const sobj = { ...user, ...psearch };
        return sobj[key];
    }
    return value;
}

/*
 * 重写时间的toJSON方法，因为在调用JSON.stringify的时候，时间转换就调用的toJSON，这样会导致少8个小时，所以重写它的toJSON方法
 */
Date.prototype.toJSON = function () {
    return this.format("yyyy-MM-dd hh:mm:ss"); // util.formatDate是自定义的个时间格式化函数
}

Date.prototype.first = function (tp) {
    return firstDate(this, tp);
}

Date.prototype.last = function (tp) {
    return lastDate(this, tp);
}

Date.prototype.add = function (day, tp) {
    return addDate(this, day, tp);
}

Date.prototype.diff = function (dt) {
    return betweenDay(this, dt);
}

Date.prototype.date = function () {
    return new Date(this.getFullYear(), this.getMonth(), this.getDate());
}

Date.prototype.format = function (fmt) {
    return formatDate(this, fmt);
}

Date.prototype.add = function (day, tp) {
    return addDate(this, day, tp);
}

Date.prototype.first = function (tp) {
    return firstDate(this, tp);
}

Date.prototype.last = function (tp) {
    return lastDate(this, tp);
}


export default { formatDate, addDate, firstDate, lastDate, betweenDay, getDefaultValue, parseDate }
